package com.lhy.admin.service;

import com.lhy.admin.mapper.UserRoleMapper;
import com.lhy.admin.model.User;
import com.lhy.admin.model.UserRole;
import com.lhy.admin.util.CollectionUtil;
import com.lhy.commonweb.service.AbstractService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UserRoleService extends AbstractService<UserRole, Integer> {

    @Autowired
    UserService userService;

    public UserRoleService(@Qualifier("userRoleMapper") Mapper<UserRole> mapper) {
        super(mapper);
    }

    public int deleteUserRole(String name, Set<Long> roleIds) {
        Example example = getNameRoleIdExample(name, roleIds);
        return this.delete(example);
    }

    public int addUserRole(String name, Set<Long> roleIds) {
        Example example = getNameRoleIdExample(name, roleIds);
        return this.delete(example);
    }

    private Example getNameRoleIdExample(String name, Set<Long> roleIds) {
        User cond = userService.getCond(new User().setName(name));
        Example example = new Example(UserRole.class);
        example.and().andEqualTo(UserRole.FieldEnum.USER_ID.javaFieldName(), new BigDecimal(cond.getId()).longValue())
                .andIn(UserRole.FieldEnum.ROLE_ID.javaFieldName(), roleIds);
        return example;
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateUserRole(String name, List<Long> newRoleIds) {
        User user = userService.getCond(new User().setName(name));
        long userId = new BigDecimal(user.getId()).longValue();
        log.debug("将更新角色的用户：{},{}", name, userId);
        log.debug("新roleIds:{}", CollectionUtil.toString(newRoleIds));

        UserRoleMapper mapper = getMapper();

        //查询原有roles
        List<UserRole> oldUserRoles = mapper.select(new UserRole().setUserId(userId));
        List<Long> oldUserRoleIds = oldUserRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        log.debug("已存在的roleIds:{}", CollectionUtil.toString(oldUserRoleIds));

        //需删除的userRoleIds
        List<Long> deletedUserRoleIds = oldUserRoles.stream()
                .filter(item -> !newRoleIds.contains(item.getRoleId()))
                .map(UserRole::getId)
                .collect(Collectors.toList());
        log.debug("需要删除的roleIds:{}", CollectionUtil.toString(deletedUserRoleIds));
        if (!deletedUserRoleIds.isEmpty()) {
            Example example = new Example(UserRole.class);
            example.and().andIn(UserRole.FieldEnum.ID.javaFieldName(), deletedUserRoleIds);
            mapper.deleteByExample(example);
        }

        //需要新增的
        List<UserRole> addUserRoleIds = newRoleIds.stream()
                .filter(item -> !oldUserRoleIds.contains(item))
                .map(aLong -> new UserRole().setRoleId(aLong).setUserId(userId))
                .collect(Collectors.toList());
        log.debug("需要新增的roleIds:{}", CollectionUtil.toString(addUserRoleIds));
        addUserRoleIds.forEach(mapper::insert);

    }
}
